import cloud from '@lafjs/cloud'
let dbName = "web-course"
const db = cloud.mongo.db
import { readFile } from 'node:fs/promises'
//const db = cloud.database();
let data

export default async function (ctx: FunctionContext) {
  data = ctx.body.data
  switch (ctx.body.type) {
    case "add":
      return add()
      break;
    case "update":
      return update()
      break;
    case "del":
      return delFunc()
      break;
    case "list":
      return list()
      break;
    case "details":
      return details()
      break;
    case "getSignUpInfo":
      return getSignUpInfo()
      break;
    case "getUnlimitedQRCode"://小程序太阳码
      return getUnlimitedQRCode()
      break;
    default://不分页查询
      return Search()
      break;
  }
}

async function getUnlimitedQRCode() {
  let access_token = await getAccessToken()
  const response = await cloud.fetch({
    url: `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${access_token}`,
    method: 'POST',
    data: { page: "packagePages/curriculum/details", "scene": data.scene },
    headers: { 'Content-Type': 'application/json' },
    responseEncoding: "base64", //重点
  });
  return cloud.utils.requestReturn({ data: "data:image/png;base64," + response.data })


  // 获取微信小程序的access token
  async function getAccessToken() {
    const response = await cloud.fetch.get('https://api.weixin.qq.com/cgi-bin/token', {
      params: {
        grant_type: 'client_credential',
        appid: "wx9c3827b9e4e2ea96",
        secret: "122cfacb5c3fdab083f0e354b13f8365",
      }
    });
    const { access_token } = response.data;
    return access_token
  }
}

async function details() {
  let res = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: data
  });
  return cloud.utils.requestReturn({ data: res })
}

async function add() {
  await cloud.nw.db.add({
    dbName,
    dataJson: data,
    cancelAddTime: true
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function list() {
  console.log("data", data)
  let query = cloud.utils.fuzzyQuery({ ...data })

  if (data.type && data.type.length) {
    let aa = data.type[data.type.length - 1]
    query.type = { $in: [aa] }
  }
  console.log("筛选入参", query)


  let res = await cloud.nw.db.select({
    dbName,
    getCount: true,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize,
    whereJson: query,
    fieldJson: {
      needUserParams: false,
    },
    sortArr: [{ "name": "sort", "type": "asc" }],
  });
  return cloud.utils.requestReturn({ data: res })
}

async function delFunc() {
  await cloud.nw.db.del({
    dbName,
    whereJson: { _id: data._id }
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function update() {
  let query = { ...data }
  delete query._id
  await cloud.nw.db.update({
    dbName,
    whereJson: {
      _id: data._id,
    },
    dataJson: query
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function Search() {
  let obj = {}
  let fieldJson = {}
  if (data && data.hasOwnProperty('allData')) {
    fieldJson = { needUserParams: 0, lessonContent: 0 }
  } else {
    fieldJson = { needUserParams: 0 }
    obj["status"] = { $ne: 0 }
  }
  let aa = await db.collection(dbName)
    .find(obj)
    .project(fieldJson)// 过滤掉不需要的字段
    .sort({ sort: 1 })
    .toArray()
  return cloud.utils.requestReturn({ data: aa })
}

async function getSignUpInfo() {
  let resp = await cloud.nw.db.findByWhereJson({
    dbName,
    fieldJson: { needUserParams: true },
    whereJson: { _id: data._id },
  });
  return cloud.utils.requestReturn({ data: resp })
}
